<template>
    <div class="map-container" ref="mapContainer"></div>
</template>

<script setup>
import { ref, onMounted, watch, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';
import 'echarts/extension/bmap/bmap';
import china from '@/assets/maps/china.json' // 修改为JSON文件导入

const props = defineProps({
    mapData: {
        type: Array,
        required: true,
        default: () => []
    }
});

const mapContainer = ref(null);
let chart = null;

const initChart = () => {
    if (!mapContainer.value) return;

    chart = echarts.init(mapContainer.value);

    // 模拟中国地图数据
    const option = {
        tooltip: {
            trigger: 'item',
            formatter: function (params) {
                const data = params.data;
                return `
            <div style="font-weight: bold; margin-bottom: 5px;">${data.name}</div>
            <div>AQI: ${data.value[2]}</div>
            <div>状态: ${data.status}</div>
            <div>更新时间: ${data.updateTime}</div>
          `;
            }
        },
        visualMap: {
            min: 0,
            max: 300,
            calculable: true,
            inRange: {
                color: ['#00FF00', '#00FFFF', '#FFD700', '#FF8C00', '#FF0000', '#800080']
            },
            textStyle: {
                color: '#333'
            }
        },
        geo: {
            map: 'china',
            roam: true,
            zoom: 1.2,
            center: [104.114129, 37.550339],
            label: {
                emphasis: {
                    show: false
                }
            },
            itemStyle: {
                normal: {
                    areaColor: '#d6e4ff',      // 更有色彩感的浅蓝灰，让地图轮廓自然清晰
                    borderColor: '#666666'     // 更深的灰色，增强省份边界可读性
                },
                emphasis: {
                    areaColor: '#91caff'       // 明亮蓝色，高亮明显、视觉聚焦强
                }
            }
        },
        series: [
            {
                name: '监测站点',
                type: 'scatter',
                coordinateSystem: 'geo',
                data: props.mapData.map(item => {
                    return {
                        name: item.name,
                        value: [item.longitude, item.latitude, item.aqi],
                        status: item.status,
                        updateTime: item.updateTime,
                        symbolSize: item.aqi / 8 + 6,
                        itemStyle: {
                            color: getColorByAQI(item.aqi)
                        }
                    };
                }),
                label: {
                    formatter: '{b}',
                    position: 'right',
                    show: false
                },
                emphasis: {
                    label: {
                        show: true
                    }
                }
            },
            {
                name: '站点连接',
                type: 'lines',
                coordinateSystem: 'geo',
                zlevel: 2,
                effect: {
                    show: true,
                    period: 6,
                    trailLength: 0.7,
                    color: '#1890ff',
                    symbolSize: 3
                },
                lineStyle: {
                    color: '#1890ff',
                    width: 1,
                    opacity: 0.6,
                    curveness: 0.2
                },
                data: generateLinesData(props.mapData)
            }
        ],
        animation: true,
        animationDuration: 1000,
        animationEasing: 'cubicInOut'
    };

    chart.setOption(option);

    window.addEventListener('resize', resizeChart);
};

const getColorByAQI = (aqi) => {
    if (aqi <= 50) return '#00FF00';    // 鲜绿色
    if (aqi <= 100) return '#00FFFF';   // 青色
    if (aqi <= 150) return '#FFD700';   // 金黄色
    if (aqi <= 200) return '#FF8C00';   // 深橙色
    if (aqi <= 300) return '#FF0000';   // 红色
    return '#800080';                   // 紫色
};

const generateLinesData = (stations) => {
    const lines = [];
    const centralStations = stations.filter(station => station.isMainStation);

    if (centralStations.length > 0) {
        const otherStations = stations.filter(station => !station.isMainStation);

        centralStations.forEach(central => {
            otherStations.forEach(station => {
                if (Math.random() > 0.7) { // 随机生成部分连线
                    lines.push({
                        coords: [
                            [central.longitude, central.latitude],
                            [station.longitude, station.latitude]
                        ]
                    });
                }
            });
        });
    }

    return lines;
};

const updateChart = () => {
    if (!chart) return;

    chart.setOption({
        series: [
            {
                data: props.mapData.map(item => {
                    return {
                        name: item.name,
                        value: [item.longitude, item.latitude, item.aqi],
                        status: item.status,
                        updateTime: item.updateTime,
                        symbolSize: item.aqi / 10 + 5,
                        itemStyle: {
                            color: getColorByAQI(item.aqi)
                        }
                    };
                })
            },
            {
                data: generateLinesData(props.mapData)
            }
        ]
    });
};

const resizeChart = () => {
    chart && chart.resize();
};

watch(() => props.mapData, () => {
    updateChart();
}, { deep: true });

onMounted(() => {
    // 模拟加载中国地图
    echarts.registerMap('china', china);

    initChart();
});

onBeforeUnmount(() => {
    if (chart) {
        chart.dispose();
        chart = null;
    }
    window.removeEventListener('resize', resizeChart);
});
</script>

<style scoped>
.map-container {
    width: 100%;
    height: 400px;
}
</style>